--[[ Copyright 2012, Chris Ho                               ]]--
--[[ MIT License (Please read the LICENSE file for details) ]]--

Use("common/Const");
Use("common/Log");
Use("common/Position");
Use("common/Creature");
Use("common/Skill");
Use("common/Task");

-- Retreat from a destination
-- progress: progress state
-- id: who is responsible for the task
-- origin: where the task started
-- time: when the task started
-- hp: hit points at task creation
-- sp: skill points at task creation
-- resilience: modified resilience value
-- tranquility: modified tranquility value
-- hotspot: desired position to run from
Retreat = {};

function Retreat.Create(_pet, _hotspot)
  local instance = Task.Create(_pet);

  instance.resilience = _pet:GetResilience();
  instance.tranquility = _pet:GetTranquility();
  instance.hotspot = _hotspot;

  --[[ Go to Destination ]]--
  function instance:Execute()
    Debug("Retreat.Execute()");

    if (GetV(V_HP, self.id) < (self.hp / self.resilience)) then
      -- We've taken a lot of damage since the task began. Abandon this
      -- task and try to do something else.
      Info("Retreat.Execute() interrupting task")
      return self:Progress(PROGRESS_FAILURE);
    end

    -- Try to keep a minimum range. When retreating, we've "arrived" when we're
    -- at least at tranquility range.
    local range = self.tranquility;
    if (range > LEASH) then range = LEASH end
    if (range > VISIBILITY) then range = VISIBILITY end
    return self:Progress(self:Withdraw(self.hotspot, range));
  end

  return instance;
end
